package com.mayikt.redislistener;

import com.mayikt.constant.PayConstant;
import com.mayikt.entity.PayTokenLogEntity;
import com.mayikt.entity.PaymentTransactionEntity;
import com.mayikt.mapper.PayTokenLogMapper;
import com.mayikt.mapper.PaymentTransactionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private PayTokenLogMapper payTokenLogMapper;
    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String tokenKey = message.toString();
        PayTokenLogEntity payTokenLogEntity = payTokenLogMapper.selectPayTokenLog(tokenKey);
        if (payTokenLogEntity == null) {
            return;
        }
        // 获取支付id
        String paymentId = payTokenLogEntity.getPaymentId();
        // 根据支付id查询支付的详细信息
        PaymentTransactionEntity pte = paymentTransactionMapper.selectByPaymentId(paymentId);
        if (pte == null) {
            return;
        }
        // 如果是为待支付情况下 ,则将该笔订单改为已经超时
        if (!(PayConstant.PAY_STAY_STATUS.equals(pte.getPaymentStatus()))) {
            return;
        }
        // 调用第三方支付接口再次确认下即可，可以根据用户行为判断支付渠道
        int result = paymentTransactionMapper.updatePaymentOvertimeStatus(paymentId);
        if (result > 0) {
            // 调用库存接口增加库存 ---
        }
    }
}